<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
            <!--      编辑状态-->
            <a-modal
                :visible="state.editStatusVisible"
                title="编辑项目实施情况"
                centered
                @ok="confirmItemStatus"
                @cancel="cancelItem"
                width="300px"
            >
                <a-radio-group v-model:value="state.itemStatus">
                    <a-radio :style="radioStyle" value="planning"
                        ><div class="color-father">项目计划<div class="finish-box no-margin"></div></div
                    ></a-radio>
                    <a-radio :style="radioStyle" value="normal"
                        ><div class="color-father">正常进行<div class="running-box no-margin"></div></div
                    ></a-radio>
                    <a-radio :style="radioStyle" value="extension"
                        ><div class="color-father">进度延迟<div class="daily-box no-margin"></div></div
                    ></a-radio>
                </a-radio-group>
            </a-modal>
            <!--      编辑状态-->
            <!--      默认开始时间-->
            <a-modal
                :visible="state.timeVisible"
                title="默认开始月份"
                centered
                @ok="confirmStartTime"
                :confirm-loading="state.timeLoading"
                @cancel="cancelStartTime"
            >
                <a-form :model="state" ref="timeRef">
                    <a-form-item
                        label="默认开始月份"
                        :rules="[{ required: true, message: '请选择默认开始月份', trigger: 'blur' }]"
                        name="timeRange"
                    >
                        <a-date-picker
                            style="width: 100%"
                            v-model:value="state.timeRange"
                            value-format="YYYY-MM"
                            picker="month"
                        />
                    </a-form-item>
                </a-form>
            </a-modal>
            <!--      默认开始时间-->
            <div class="body">
                <div class="top-tab">
                    <a-radio-group v-model:value="state.radioValue" button-style="solid" @change="radioChange">
                        <a-radio-button v-for="(item, index) in state.tabList" :value="item.id">{{
                            item.regionName
                        }}</a-radio-button>
                    </a-radio-group>
                </div>
                <div class="table-tip">
                    <div class="left-top">
                        <div class="finish"><span class="tip-msg">项目计划</span><div class="finish-box"></div></div>
                        <div class="running"><span class="tip-msg">正常进行</span><div class="running-box"></div></div>
                        <div class="daily"><span class="tip-msg">进度延迟</span><div class="daily-box"></div></div>
                    </div>
                    <div class="right-top">
                        <a-space>
                            <a-button style="margin: 15px 0" type="primary" @click="exportToPDF"> 导出</a-button>
                            <a-button type="primary" @click="handleChangeTime">默认开始时间</a-button>
                            <a-button type="primary" v-if="!state.isEditTable" @click="handleEditStart">编辑</a-button>
                            <a-button type="primary" v-else @click="state.isEditTable = false">完成</a-button>
                        </a-space>
                    </div>
                </div>

                <div class="main">
                    <div class="no-data-img" v-if="state.radioValue === ''">
                        <svg
                            xmlns="http://www.w3.org/2000/svg"
                            xmlns:xlink="http://www.w3.org/1999/xlink"
                            width="265px"
                            height="192px"
                            viewBox="0 0 265 192"
                            version="1.1"
                        >
                            <title>暂无待办事项</title>
                            <defs>
                                <linearGradient
                                    x1="50%"
                                    y1="85.1278551%"
                                    x2="50%"
                                    y2="-24.3022005%"
                                    id="linearGradient-1"
                                >
                                    <stop stop-color="#3875FF" stop-opacity="0" offset="0%" />
                                    <stop stop-color="#3875FF" stop-opacity="0.2" offset="100%" />
                                </linearGradient>
                                <linearGradient
                                    x1="50%"
                                    y1="85.1278551%"
                                    x2="50%"
                                    y2="-24.3022005%"
                                    id="linearGradient-2"
                                >
                                    <stop stop-color="#3875FF" stop-opacity="0" offset="0%" />
                                    <stop stop-color="#3875FF" stop-opacity="0.2" offset="100%" />
                                </linearGradient>
                                <linearGradient
                                    x1="50%"
                                    y1="85.1278551%"
                                    x2="50%"
                                    y2="-24.3022005%"
                                    id="linearGradient-3"
                                >
                                    <stop stop-color="#3875FF" stop-opacity="0" offset="0%" />
                                    <stop stop-color="#3875FF" stop-opacity="0.2" offset="100%" />
                                </linearGradient>
                                <linearGradient x1="50%" y1="50%" x2="50%" y2="-4.79965365%" id="linearGradient-4">
                                    <stop stop-color="#3875FF" stop-opacity="0" offset="0%" />
                                    <stop stop-color="#3875FF" stop-opacity="0.1" offset="100%" />
                                </linearGradient>
                                <linearGradient x1="100%" y1="50%" x2="0%" y2="50%" id="linearGradient-5">
                                    <stop stop-color="#9CBEF7" offset="0%" />
                                    <stop stop-color="#96D1F7" offset="100%" />
                                </linearGradient>
                                <linearGradient x1="100%" y1="50%" x2="0%" y2="50%" id="linearGradient-6">
                                    <stop stop-color="#9CBEF7" offset="0%" />
                                    <stop stop-color="#96D1F7" offset="100%" />
                                </linearGradient>
                            </defs>
                            <g id="页面-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                <g id="审批管理-暂无待办事项" transform="translate(-927, -470)">
                                    <g id="暂无待办事项" transform="translate(927, 470)">
                                        <g id="编组-69备份-3备份-3" fill-rule="nonzero">
                                            <path
                                                d="M30.4,70.4 C38.3897145,70.4 44.9396432,76.4022329 45.5530639,84.0283112 C45.8323774,84.0092712 46.1150286,84 46.4,84 C53.027417,84 58.4,89.0144112 58.4,95.2 C58.4,101.385589 53.027417,106.4 46.4,106.4 C46.1313282,106.4 45.8647188,106.391759 45.6004459,106.375534 L45.6,107.2 L8.8,107.2 L8.80006856,105.99739 C3.72613437,104.690379 0,100.351322 0,95.2 C0,89.0144112 5.372583,84 12,84 C13.1159648,84 14.1963502,84.1421776 15.2214963,84.4081848 C15.6437054,76.6027782 22.2779069,70.4 30.4,70.4 Z"
                                                id="形状结合备份"
                                                fill="url(#linearGradient-1)"
                                            />
                                            <path
                                                d="M174.4,35.2 L174.400166,35.1009906 C168.085987,34.3137074 163.2,28.9274454 163.2,22.4 C163.2,15.3307552 168.930755,9.6 176,9.6 C177.223344,9.6 178.406604,9.77161808 179.527019,10.0920919 C181.87653,4.17968127 187.650157,0 194.4,0 C202.141022,0 208.598072,5.49733733 210.080147,12.8010091 C216.449395,12.8415186 221.6,17.8400063 221.6,24 C221.6,30.0561716 216.621551,34.98966 210.40049,35.1934501 L210.4,35.2 L174.4,35.2 Z"
                                                id="形状结合"
                                                fill="url(#linearGradient-2)"
                                                transform="translate(192.4, 17.6) scale(-1, 1) translate(-192.4, -17.6)"
                                            />
                                            <path
                                                d="M242.8,47.2 C247.491543,47.2 251.362882,50.7117164 251.928816,55.249951 C252.214523,55.2167339 252.505192,55.2 252.8,55.2 C256.77645,55.2 260,58.2444637 260,62 C260,65.7555363 256.77645,68.8 252.8,68.8 C252.529676,68.8 252.262831,68.7859302 252.000242,68.7585236 L252,69.6 L229.6,69.6 L229.600068,68.6315132 C226.393652,67.9443906 224,65.2361993 224,62 C224,58.2444637 227.22355,55.2 231.2,55.2 C232.054514,55.2 232.874259,55.3405911 233.634718,55.5986176 C234.040539,50.892793 237.989021,47.2 242.8,47.2 Z"
                                                id="形状结合备份-2"
                                                fill="url(#linearGradient-3)"
                                            />
                                            <g id="编组-50" transform="translate(1.6, 76.8)">
                                                <ellipse
                                                    id="椭圆形"
                                                    fill="url(#linearGradient-4)"
                                                    cx="131.6"
                                                    cy="57.6"
                                                    rx="131.6"
                                                    ry="57.6"
                                                />
                                                <g id="编组-46" transform="translate(30.4, 4.8)">
                                                    <rect
                                                        id="矩形"
                                                        fill="#D7E3FF"
                                                        x="6.4"
                                                        y="20"
                                                        width="2.4"
                                                        height="12"
                                                    />
                                                    <path
                                                        d="M8.4,21.5460356 C25.469423,21.5460356 11.8000002,-1.42108547e-14 8.4,-1.42108547e-14 C4.99999998,-1.42108547e-14 -8.66942296,21.5460356 8.4,21.5460356 Z"
                                                        id="椭圆形"
                                                        fill="#EAF0FF"
                                                    />
                                                </g>
                                                <g id="编组-46备份-2" transform="translate(218.4, 4.8)">
                                                    <rect
                                                        id="矩形"
                                                        fill="#D7E3FF"
                                                        x="4.97664"
                                                        y="13.824"
                                                        width="1.65888"
                                                        height="8.2944"
                                                    />
                                                    <path
                                                        d="M5.80608,14.8926198 C17.6044651,14.8926198 8.15616008,-9.8225428e-15 5.80608,-9.8225428e-15 C3.45599989,-9.8225428e-15 -5.99230512,14.8926198 5.80608,14.8926198 Z"
                                                        id="椭圆形"
                                                        fill="#EAF0FF"
                                                    />
                                                </g>
                                                <g id="编组-46备份" transform="translate(245.6, 21.6)">
                                                    <rect
                                                        id="矩形"
                                                        fill="#D7E3FF"
                                                        x="3.6"
                                                        y="10"
                                                        width="1.2"
                                                        height="6"
                                                    />
                                                    <path
                                                        d="M4.2,10.7730178 C12.7347114,10.7730178 5.90000008,-7.10542736e-15 4.2,-7.10542736e-15 C2.5,-7.10542736e-15 -4.33471146,10.7730178 4.2,10.7730178 Z"
                                                        id="椭圆形"
                                                        fill="#EAF0FF"
                                                    />
                                                </g>
                                            </g>
                                        </g>
                                        <g id="编组-61" transform="translate(89.6, 21.6)">
                                            <ellipse
                                                id="椭圆形"
                                                fill="#E2EBFF"
                                                fill-rule="nonzero"
                                                cx="42.8"
                                                cy="80"
                                                rx="42.8"
                                                ry="4.8"
                                            />
                                            <rect
                                                id="矩形备份-91"
                                                fill="url(#linearGradient-5)"
                                                x="5.6"
                                                y="0"
                                                width="70.4"
                                                height="80.8"
                                                rx="3.2"
                                            />
                                            <g
                                                id="编组-60"
                                                transform="translate(20.8, 28)"
                                                fill="#FFFFFF"
                                                fill-rule="nonzero"
                                            >
                                                <rect id="矩形" x="0" y="0" width="40" height="3.2" rx="1.6" />
                                                <rect
                                                    id="矩形备份-92"
                                                    x="0"
                                                    y="15.2"
                                                    width="40"
                                                    height="3.2"
                                                    rx="1.6"
                                                />
                                                <rect
                                                    id="矩形备份-93"
                                                    x="0"
                                                    y="30.4"
                                                    width="40"
                                                    height="3.2"
                                                    rx="1.6"
                                                />
                                            </g>
                                            <path
                                                d="M21.6,0 L60.7346814,0 L55.7992343,8.40508424 C55.6555754,8.64973584 55.393086,8.8 55.1093744,8.8 L27.225307,8.8 C26.9415954,8.8 26.6791059,8.64973584 26.535447,8.40508424 L21.6,0 L21.6,0 Z"
                                                id="矩形"
                                                fill="#FFFFFF"
                                                fill-rule="nonzero"
                                            />
                                            <rect
                                                id="矩形备份-94"
                                                fill="url(#linearGradient-6)"
                                                x="29.6"
                                                y="0"
                                                width="23.2"
                                                height="3.2"
                                                rx="1.6"
                                            />
                                        </g>
                                    </g>
                                </g>
                            </g>
                        </svg>
                        <div class="no-data-msg">暂无数据</div>
                    </div>
                    <div class="kb-table-box" ref="contentToExport" v-else>
                        <a-table
                            :columns="columns"
                            :dataSource="state.dataSource"
                            :scroll="{ x: 'max-content', y: '60vh' }"
                            :pagination="false"
                            ref="tableRef"
                            :loading="state.tableLoading"
                        >
                            <template #bodyCell="{ record, text, column }">
                                <template v-if="column.dataIndex === 'milepostName'">{{ text }}</template>
                                <template v-else-if="column.dataIndex === 'time'">
                                    <div class="time-div">
                                        <div class="plan-time">计划</div>
                                        <div class="reality-time">实际</div>
                                    </div>
                                </template>
                                <template v-else>
                                    <div class="record-div">
                                        <div class="record-top">
                                            <div class="default-status-div">
                                                <div
                                                    class="inner"
                                                    @click="changeItem(record, text, 'first', 'plan')"
                                                    :style="getStyle(text, 'first', 'plan')"
                                                ></div>
                                            </div>

                                            <div class="default-status-div">
                                                <div
                                                    class="inner"
                                                    @click="changeItem(record, text, 'second', 'plan')"
                                                    :style="getStyle(text, 'second', 'plan')"
                                                ></div>
                                            </div>
                                            <div class="default-status-div">
                                                <div
                                                    class="inner"
                                                    @click="changeItem(record, text, 'third', 'plan')"
                                                    :style="getStyle(text, 'third', 'plan')"
                                                ></div>
                                            </div>
                                            <div class="default-status-div">
                                                <div
                                                    class="inner"
                                                    @click="changeItem(record, text, 'fourth', 'plan')"
                                                    :style="getStyle(text, 'fourth', 'plan')"
                                                ></div>
                                            </div>
                                        </div>
                                        <div class="record-bottom">
                                            <div class="default-status-div">
                                                <div
                                                    class="inner"
                                                    @click="changeItem(record, text, 'first', 'reality')"
                                                    :style="getStyle(text, 'first', 'reality')"
                                                ></div>
                                            </div>

                                            <div class="default-status-div">
                                                <div
                                                    class="inner"
                                                    @click="changeItem(record, text, 'second', 'reality')"
                                                    :style="getStyle(text, 'second', 'reality')"
                                                ></div>
                                            </div>
                                            <div class="default-status-div">
                                                <div
                                                    class="inner"
                                                    @click="changeItem(record, text, 'third', 'reality')"
                                                    :style="getStyle(text, 'third', 'reality')"
                                                ></div>
                                            </div>
                                            <div class="default-status-div">
                                                <div
                                                    class="inner"
                                                    @click="changeItem(record, text, 'fourth', 'reality')"
                                                    :style="getStyle(text, 'fourth', 'reality')"
                                                ></div>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
            </div>

            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    import html2canvas from 'html2canvas'
    import jsPDF from 'jspdf'
    import { nextTick } from 'vue'
    // onMounted(() => {
    //   // const monthIndex = dynamicColumns.findIndex(col => col.dataIndex === defaultMonth);
    //   // if (monthIndex !== -1 && tableRef.value) {
    //   //   const scrollWidth = 150 * monthIndex; // 计算横向滚动距离
    //   //   tableRef.value.$el.querySelector('.ant-table-body').scrollLeft = scrollWidth;
    //   // }
    //   getRegionList()
    //  getData()
    // });
    onMounted(async () => {
        await getRegionList() // 等待 getRegionList 执行完成
        getData() // getRegionList 执行完成后再调用 getData
        getPermission()
    })
    const radioStyle = reactive({
        display: 'flex',
        height: '30px',
        lineHeight: '30px'
    })
    const state = reactive({
        exportLoading: false,
        tabList: [],
        radioValue: '',
        isEditTable: false,
        dataSource: [],
        timeVisible: false,
        editStatusVisible: false,
        itemStatus: '',
        timeRange: '',
        timeLoading: false,
        tableLoading: false,
        permission: false
    })
    const editItemParams = ref({
        rowMetaId: undefined,
        headerId: undefined,
        weekName: undefined,
        planType: undefined, //计划还是实际
        proress: undefined,
        configAreaId: undefined
    })
    const defaultMonth = '2024-06' // 设置默认展示月份
    const dynamicColumns = []

    const currentColumns = [
        {
            title: '项目阶段',
            dataIndex: 'milepostName',
            fixed: 'left',
            align: 'center',
            width: '120px',
            ellipsis: true,
            customCell: item => {
                const { rowIndex, rowSpan } = item
                return {
                    rowSpan: rowSpan,
                    style: {
                        fontSize: '16px',
                        color: '#262626',
                        fontWeight: '600',
                        borderRight: '1px solid #ececec',
                        backgroundColor: '#F7FAFF'
                    }
                }
            }
        },
        {
            'title': '时间',
            'dataIndex': 'time',
            'projectId': null,
            'actionTaskNumber': null,
            'sceneProjectId': null,
            'scene': false,
            fixed: 'left',
            width: 60,
            align: 'center',
            customCell: item => {
                return {
                    style: {
                        borderRight: '1px solid #ececec',
                        backgroundColor: '#F7FAFF'
                    }
                }
            }
        }
    ]
    const columns = ref([])
    const tableRef = ref(null)

    const content = ref(null)
    // const exportToPDF = () => {
    //   html2canvas(content.value, {
    //     scale: 2, // 提高 canvas 的分辨率
    //     useCORS: true, // 处理跨域问题
    //   }).then((canvas) => {
    //     const imgData = canvas.toDataURL('image/png');
    //     const pdf = new jsPDF({
    //       orientation: 'portrait',
    //       unit: 'mm',
    //       format: 'a4'
    //     });
    //
    //     const imgWidth = 210;
    //     const imgHeight = canvas.height * imgWidth / canvas.width;
    //
    //     pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
    //     pdf.save('download.pdf');
    //   });
    // };
    // const exportToPDF = async () => {
    //     state.exportLoading = true
    //     await nextTick() // 确保表格渲染完毕
    //
    //     const tableElement = tableRef.value.$el
    //     const originalWidth = tableElement.style.width
    //
    //     // 展开表格，使所有内容可见
    //     tableElement.style.width = tableElement.scrollWidth + 'px'
    //
    //     // 生成 PDF
    //     html2canvas(tableElement, {
    //         scale: 2,
    //         useCORS: true
    //     })
    //         .then(canvas => {
    //             const imgData = canvas.toDataURL('image/png')
    //             const pdf = new jsPDF({
    //                 orientation: 'landscape', // 横向
    //                 unit: 'mm',
    //                 format: 'a4'
    //             })
    //
    //             const imgWidth = 297 // A4 纸宽度在横向模式下为 297mm
    //             const imgHeight = (canvas.height * imgWidth) / canvas.width
    //
    //             pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight)
    //             pdf.save('table.pdf')
    //
    //             // 还原表格宽度
    //             tableElement.style.width = originalWidth
    //         })
    //         .finally(() => {
    //             state.exportLoading = false
    //         })
    // }
    function groupData(data) {
        let milepostName = ''
        if (!data || !data.length) {
            return []
        }
        return data.map((item, index) => {
            if (milepostName !== item.milepostName) {
                milepostName = item.milepostName
                let rowSpan = 0
                for (let i = 0; i < data.length; i++) {
                    if (i >= index) {
                        if (milepostName === data[i].milepostName) {
                            rowSpan += 1
                        } else {
                            break
                        }
                    }
                }
                item.rowSpan = rowSpan
                item.border = index
            } else {
                item.rowSpan = 0
            }
            item.rowIndex = index
            return item
        })
    }
    function formattedData(data) {
        state.dataSource = data.map(item => {
            const formattedItem = {}

            // 遍历原始 item 中的所有字段，并复制到 formattedItem 中
            for (const key in item) {
                if (item.hasOwnProperty(key)) {
                    if (key === 'projectDataMap' && typeof item[key] === 'object' && item[key] !== null) {
                        // 特殊处理 projectDataMap 字段
                        for (const projectName in item[key]) {
                            const project = item[key][projectName]
                            formattedItem[projectName] = { ...project }
                        }
                    } else {
                        // 直接复制其他字段
                        formattedItem[key] = item[key]
                    }
                }
            }

            // 如果 projectDataMap 为空，添加默认值
            if (!item.projectDataMap || Object.keys(item.projectDataMap).length === 0) {
                formattedItem.projectName = ''
                formattedItem.id = ''
                formattedItem.projectProgressEnum = ''
                formattedItem.remarks = null
                formattedItem.rowSpan = ''
                formattedItem.projectId = ''
                formattedItem.taskId = ''
                formattedItem.riskCount = ''
                formattedItem.taskOwner = ''
                formattedItem.actionTaskCount = ''
                formattedItem.plan = {
                    first: 'extension',
                    second: 'planning',
                    third: 'normal',
                    fourth: 'extension'
                }
                formattedItem.reality = {
                    first: 'extension',
                    second: 'planning',
                    third: 'normal',
                    fourth: 'extension'
                }
            }

            return formattedItem
        })
    }
    const colorMap = {
        'planning': '#5E8FFE',
        'normal': '#AAE56A',
        'extension': '#FABA32',
        'default': 'rgba(0, 0, 0, 0)'
    }
    function getStyle(text, flag, type) {
        if (type === 'plan') {
            if (text.plan) {
                let color = text.plan[flag]
                // console.log(color,'color');
                let finllyColor = colorMap[color]
                // console.log(finllyColor,'finllyColor');
                return {
                    backgroundColor: finllyColor
                }
            } else {
                return
            }
        } else {
            if (text.reality) {
                let color = text.reality[flag]
                let finllyColor = colorMap[color]
                return {
                    backgroundColor: finllyColor
                }
            } else {
                return
            }
        }
    }
    // 默认展示日期
    function handleChangeTime() {
        state.timeVisible = true
        state.timeRange = columns.value[2].title
    }
    // 区域
    async function getRegionList() {
        try {
            const data = await get('/solution-ppm/api/v2/built-in-system-ppm/cooperation/config_region/display')
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.tabList = data.data
            state.radioValue = data.data[0]?.id || ''
        } catch (error) {
            message.error('Failed to fetch region list')
        }
    }
    //     切换区域
    function radioChange() {
        getData()
    }
    // 获取数据
    function getData() {
        state.tableLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/gantt/search', {
            configAreaId: state.radioValue
        })
            .then(data => {
                if (data.code !== 200) {
                    state.dataSource = []
                    message.error(data.message)
                    return
                }
                columns.value = data.data.columns
                columns.value.forEach(item => {
                    if (item.dataIndex === 'time') {
                        item.width = 60
                    }
                    item.width = 154
                    ;(item.align = 'center'), (item.title = item.tilte)
                })
                columns.value = [...currentColumns, ...columns.value]
                // state.dataSource = groupData(data.data.dataSource)
                state.dataSource = data.data.dataSource
                formattedData(state.dataSource)
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    // 权限
    function getPermission() {
        get('/solution-ppm/api/v2/built-in-system-ppm/gantt/check_modify_permission').then(data => {
            state.permission = data.data
        })
    }
    // 改状态
    function changeItem(record, text, weekName, flag) {
        if (!state.isEditTable) {
            return
        }
        state.editStatusVisible = true
        editItemParams.value.rowMetaId = record.id
        editItemParams.value.headerId = text.projectId
        editItemParams.value.planType = flag
        editItemParams.value.weekName = weekName
        editItemParams.value.configAreaId = state.radioValue
        state.itemStatus = flag === 'reality' ? text.reality[weekName] : text.plan[weekName]
    }
    // 确定更改
    function confirmItemStatus() {
        post('/solution-ppm/api/v2/built-in-system-ppm/gantt/gantt/modify', {
            ...editItemParams.value,
            progress: state.itemStatus
        }).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success('修改成功')
            state.editStatusVisible = false
            getData()
        })
    }
    // 取消修改
    function cancelItem() {
        state.editStatusVisible = false
        state.itemStatus = ''
    }
    const pageHtml = ref('')
    const pageCss = ref('')
    function exportPageAsHTML() {
        const content = document.querySelector('.kb-table-box')
        pageHtml.value = content ? content.outerHTML : ''

        // 提取样式
        const styleSheets = Array.from(document.styleSheets)
        const cssRules = styleSheets.flatMap(sheet => Array.from(sheet.cssRules || []).map(rule => rule.cssText))
        pageCss.value = cssRules.join(' ')
        pageHtml.value = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Exported Document</title>
            <style>${pageCss.value}</style>
        </head>
        <body>
            ${pageHtml.value}
        </body>
        </html>
      `
        console.log(pageHtml.value)
        console.log(pageCss.value)
        //       // 获取需要导出的 DOM 节点
        //       const element = document.querySelector('.kb-table-box')
        //
        //       // 获取页面的 HTML 内容
        //       const htmlContent = element.outerHTML
        //
        //       // 获取页面的样式
        //       const styles = Array.from(document.styleSheets)
        //           .map(styleSheet => {
        //               try {
        //                   return Array.from(styleSheet.cssRules)
        //                       .map(rule => rule.cssText)
        //                       .join('')
        //               } catch (e) {
        //                   // 处理跨域或其他样式表加载问题
        //                   return ''
        //               }
        //           })
        //           .join('')
        //
        //       // 包装完整的 HTML 文档结构
        //       const completeHtml = `
        //   <html>
        //     <head>
        //       <style>${styles}</style>
        //     </head>
        //     <body>
        //       ${htmlContent}
        //     </body>
        //   </html>
        // `
        //
        //       // 创建一个 Blob 对象并下载文件
        //       const blob = new Blob([completeHtml], { type: 'text/html' })
        //     console.log(blob,'asdasd');
        //       const link = document.createElement('a')
        //       link.href = URL.createObjectURL(blob)
        //       link.download = 'exported_page.html'
        //       document.body.appendChild(link)
        //       link.click()
        //       document.body.removeChild(link)
    }
    const timeRef = ref(null)
    //     修改默认开始月份
    function confirmStartTime() {
        timeRef.value.validate().then(() => {
            state.timeLoading = true
            post('/solution-ppm/api/v2/built-in-system-ppm/gantt/config/modify', {
                configAreaId: state.radioValue,
                startMonth: state.timeRange
            })
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success('设置成功')
                    state.timeVisible = false
                    getData()
                    state.timeRange = ''
                })
                .finally(() => {
                    state.timeLoading = false
                })
        })
    }
    // 取消修改默认月份
    function cancelStartTime() {
        state.timeVisible = false
        state.timeRange = ''
    }
    const contentToExport = ref(null)
    // const exportToPDF = async () => {
    //     if (contentToExport.value) {
    //         // 使用 html2canvas 将内容转换为 Canvas
    //         const canvas = await html2canvas(contentToExport.value, { scale: 2 })
    //         const imgData = canvas.toDataURL('image/png')
    //
    //         // 创建 jsPDF 实例
    //         const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' })
    //
    //         const imgWidth = 210 // A4 纸张宽度
    //         const pageHeight = 295 // A4 纸张高度
    //         const imgHeight = (canvas.height * imgWidth) / canvas.width
    //         let heightLeft = imgHeight
    //         let position = 0
    //
    //         // 添加第一页
    //         pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
    //         heightLeft -= pageHeight
    //
    //         // 添加更多页面
    //         while (heightLeft > 0) {
    //             position = heightLeft - imgHeight
    //             pdf.addPage()
    //             pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
    //             heightLeft -= pageHeight
    //         }
    //
    //         // 保存 PDF
    //         pdf.save('document.pdf')
    //     }
    // }
    // TODO:导出方法
    function downloadPdf(response, name) {
        const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
        })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = name // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href)
        return href
    }

    function exportToPDF() {
        post(
            `/solution-ppm/api/v2/built-in-system-ppm/gantt/export_pdf`,
            {
                configAreaId: state.radioValue
            },
            {
                responseType: 'arraybuffer'
            }
        ).then(res => {
            let name = state.tabList.find(item => item.id == state.radioValue).regionName
            if (name) {
                downloadPdf(res, `${name}.pdf`)
            } else {
                downloadPdf(res, '进度详情.pdf')
            }
        })
    }
    function handleEditStart() {
        if (!state.permission) {
            message.info('暂无权限')
            return
        }
        state.isEditTable = true
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }

    /*样式*/

    .body {
        background-color: #f0f2f5;
    }
    .top-tab {
        height: 65px;
        padding: 16px 24px;
        background-color: #fff;
        margin-bottom: 16px;
        border-radius: 2px;
    }
    .kb-table-box {
        padding: 0 24px;
        border-radius: 2px;
        background-color: #fff;
    }
    .time-div {
        display: flex;
        flex-direction: column;
        height: 65px;
    }
    .reality-time,
    .plan-time {
        height: 32px;
        width: 100%;
        text-align: center;
        line-height: 32px;
    }
    .plan-time {
        border-bottom: 1px solid #d9d9d9;
    }
    .kb-table-box:deep(.@{ant-prefix}-table-thead) > tr > th {
        background-color: #ebf1ff;
        color: #262626;
        font-weight: 600;
        padding: 17px 4px;
        border-right: 1px solid #d9d9d9 !important;
    }

    :deep(.kb-table-box .ant3-table-tbody tr) {
        line-height: 22px;
        height: 30px;
        padding: 2px 0;
    }
    .kb-table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #595959;
        border-bottom: 1px solid #d9d9d9;
        padding: 0px 0px;
        word-break: break-all;
        background-color: #fafafa;
    }

    .record-div {
        width: 100%;
        height: 65px;
        position: relative;
        display: flex;
        flex-direction: column;
    }
    .record-div-red {
        background-color: #ff5656;
    }
    .record-top,
    .record-bottom {
        display: flex;
        height: 32px;
    }
    .record-top {
        border-bottom: 1px solid #d9d9d9;
    }
    .extension,
    .normal,
    .planning {
        width: 25%;
        height: 32px;
        background-color: orange;
    }
    .normal {
        background-color: normal;
    }
    .planning {
        background-color: planning;
    }
    .default-status-div,
    .default-status-div-last {
        width: 25%;
        height: 32px;
        position: relative;
        border-right: 1px solid #ececec;
    }
    .default-status-div-last {
        border: none;
    }
    .inner {
        height: 20px;
        background-color: #5e8ffe;
        position: absolute;
        width: calc(100% + 1px); /* 扩展宽度以覆盖右边框 */
        top: 6px;
        right: -1px; /* 向右偏移以覆盖右边框 */
    }
    .table-tip {
        background-color: #fff;
        display: flex;
        height: 65px;
        justify-content: space-between;
        padding: 0 24px;
    }

    .finish,
    .running,
    .daily {
        display: flex;
        line-height: 62px;
        margin-right: 13px;
    }

    .left-top {
        display: flex;
    }

    .right {
        flex: 1;
        display: flex;
        justify-content: end;
    }

    .finish-box,
    .running-box,
    .daily-box {
        background: #5e8ffe;
        width: 32px;
        height: 8px;
        margin-top: 26px;
    }

    .tip-msg {
        font-family: PingFangSC-Regular;
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 400;
        margin-right: 8px;
    }

    .running-box {
        background: #aae56a;
    }

    .daily-box {
        background: #faba32;
    }
    .main {
        height: calc(100vh - 300px);
        background-color: #fff;
    }
    .color-father {
        width: 100px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .no-margin {
        margin: 0;
    }
    .region-title {
        height: 26px;
        background: #fef0cc;
        border-radius: 2px;
        padding-left: 6px;
        font-size: 12px;
        color: #595959;
        line-height: 26px;
        font-weight: 400;
        margin-bottom: 16px;
    }
    .no-data-img {
        width: 264px;
        height: 192px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .no-data-msg {
        position: absolute;
        top: 60%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #595959;
    }
</style>
